package redora.client.validation;

import com.google.gwt.dom.client.NodeList;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;

public class ErrorHandler {

    public static void errorHandler(Element element, String messages) {
        if (element != null)
            DOM.setElementProperty(element.<com.google.gwt.user.client.Element> cast(),
                    "className", "validationFailedText");
        Window.alert(messages);
    }

    public static void errorHandler(FlexTable formTable, String fieldName, String messages) {
        NodeList<com.google.gwt.dom.client.Element> list = formTable.getElement()
                .getElementsByTagName("*");
        Label label = new Label(messages);
        label.setStyleName("validationFailedText");
        label.getElement().setTitle("errorMessages");
        if (fieldName != null) {
            boolean check = false;
            for (int i = 0; i < list.getLength(); i++) {
                if (list.getItem(i).getId().equalsIgnoreCase(fieldName)) {
                    for (int j = 0; j < formTable.getRowCount(); j++) {
                        if (formTable.getWidget(j, 1) != null && list.getItem(i).equals(formTable.getWidget(j, 1).getElement())) {
                            formTable.insertRow(j + 1);
                            formTable.setWidget(j + 1, 1, label);
                            j++;
                        }
                    }
                    DOM.setElementProperty(list.getItem(i).<com.google.gwt.user.client.Element> cast(),
                            "className", "validationFailedText");
                    check = true;
                } 
            }
            if (!check) {
                formTable.setWidget(formTable.getRowCount(), 1, label);
            }
        } else {
            formTable.setWidget(formTable.getRowCount(), 1, label);
        }
    }

    public static void resetFormStyle(FlexTable formTable) {
        for (int i = 0; i < formTable.getRowCount(); i++) {
            if (formTable.isCellPresent(i, 1) && formTable.getWidget(i, 1) != null) {
                formTable.getWidget(i, 1).getElement().removeClassName("validationFailedText");
                if ("errorMessages".equalsIgnoreCase(formTable.getWidget(i, 1).getTitle())) {
                    formTable.removeRow(i);
                    i--;
                }

            }
        }
    }

    public static void resetStyle(Element element) {
        element.removeClassName("validationFailedText");
    }
}
